package de.koller.million.enc.network;

import de.koller.million.enc.EncNode;
import de.koller.million.enc.EncServerRoot;
import de.koller.aframe.util.thread.ILoopHandler;
import de.koller.aframe.util.thread.ThreadRootHandle;
import de.koller.oceanFramework.OceanException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.HashSet;
import java.util.Set;

public class Network extends EncNode implements ILoopHandler {

	private final ThreadRootHandle thread = new ThreadRootHandle( "network-handle" );
	
	private ServerSocket serverSocket;
	private final Set<Connection> connections = new HashSet<>();

	public Network() {
		thread.setLoopHandler( this );
	}
	
	@Override
	public void generate( EncServerRoot root, Object... references ) {
		super.generate( root, references );

		try {
			serverSocket = new ServerSocket( Connection.PORT );
			System.out.println( "server on ip: " + InetAddress.getLocalHost().getHostAddress() );
		} catch( Exception ex ) {
			throw new OceanException( ex );
		}
		
		thread.start();
	}

	@Override
	public void loopHandle() {
		connections.add( Connection.listenForConnection( serverSocket ) );
		System.out.println( "new connection!" );
	}
	
	@Override
	public void ungenerate() {
		super.ungenerate();
		
		thread.stop();
	}

	public Set<Connection> getConnections() {
		return connections;
	}
	
}
